package com.libre.watermark;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * java实现图片文字水印效果
 *
 * https://blog.csdn.net/l854566/article/details/122008659
 **/
public class WatermarkTest {

    private static String path = System.getProperty("user.dir") + "\\src\\main\\resources\\wm\\";
    public static void main(String[] args) throws Exception {
        //读取图片
        String name = path+"bg.png";
        BufferedImage bar = ImageIO.read(new File(name));

        //设置平滑度
        Graphics2D g = bar.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        //设置水印文字字体颜色以及透明度
        g.setColor(new Color(255, 0, 0, 255));

        //设置字体格式、大小、粗细
        //获取字体格式
        //Font font = Font.createFont(Font.TRUETYPE_FONT, new File("F:\\Font\\zh32hwzyxzt.ttf"));
        //字体大小
        //font = font.deriveFont(40f);
        //字体粗细
        //font = font.deriveFont(Font.BOLD);
        Font font = new Font("宋体",Font.TRUETYPE_FONT,20);
        //设置字体
        g.setFont(font);
        // 设置水印内容
        String txt = "版权所有";
        //设置水印位置
//        int x = 3;
//        int y = 150;
        //绘制，并释放资源
//        g.drawString(txt,x,y);



        Image srcImg = ImageIO.read(new ByteArrayInputStream(image2byte(name)));
        int imgWidth = srcImg.getWidth(null);
        int imgHeight = srcImg.getHeight(null);
        int fontSize = bar.getWidth(null) / 300 * 8;

        Integer degree = 10;
        float alpha = 0.5f;
        // 设置水印旋转
        if (null != degree) {
            g.rotate(Math.toRadians(degree), (double) imgWidth / 2, (double) imgHeight / 2);
        }
        // 设置水印文字透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

        // 计算水印文字的大小
        int textWidth = fontSize * getLength(txt);
        int textHeight = fontSize;
        // 循环打印多个水印
        for (int y = -imgHeight; y < imgHeight * 2; y += textHeight + fontSize * 3) {
            for (int x = 0; x < imgWidth * 2; x += textWidth + fontSize * 3 / 2) {
                // 笫一参数-> 设置的内容,后面两个参数->文字在图片上的坐标位置
                g.drawString(txt, x, y);
            }
        }
        g.dispose();

        //保存
        ImageIO.write(bar,"png",new File(path+"aa.png"));
    }


    /**
     * 获取字符长度，一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
     *
     * @param text
     * @return 字符长度，如：text="中文",返回 2；text="test",返回 2；text="中文ABC",返回 4.
     */
    public static int getLength(String text) {
        int textLength = text.length();
        int length = textLength;
        for (int i = 0; i < textLength; i++) {
            if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
                length++;
            }
        }
        return (length % 2 == 0) ? length / 2 : length / 2 + 1;
    }
    //图片到byte数组
    public static byte[] image2byte(String path) {
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }
}
